﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AMS.UI.Controls;
using AMS.Configuration;
using DevComponents.DotNetBar.Controls;
using AMS.Common;
using System.IO;
using AMS.ComponentModel;

namespace AMS.UI.Forms
{
    /// <summary>
    /// 导出
    /// </summary>
    /// <remarks>
    /// 规则：1. 如果config为null，只能导出DataTable，否则可以导出DataTable和List类型的数据;
    /// </remarks>
    public partial class FrmExport : BaseForm, IExporter
    {
        /// <summary>
        /// 导出
        /// </summary>
        public FrmExport()
        {
            InitializeComponent();
            originalTitle = Text;
        }

        #region 属性
        private string originalTitle;
        private string exporterCaption;
        /// <summary>
        /// 子标题
        /// </summary>
        public string DataSourceName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private object dataSource;
        /// <summary>
        /// 数据源
        /// </summary>
        public object DataSource
        {
            get { return dataSource; }
            set { dataSource = value; }
        }
        /// <summary>
        /// 导出器标题
        /// </summary>
        public string ExporterCaption
        {
            get { return exporterCaption; }
            set 
            {
                exporterCaption = value;
                if (!string.IsNullOrEmpty(exporterCaption))
                {
                    Text += originalTitle + " - " + exporterCaption;
                }
                else
                {
                    Text = originalTitle;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public ListConfigInfo Config { get; set; }
        /// <summary>
        /// 显示的列信息
        /// </summary>
        private List<ColumnInfo> displayColumns;
        const int ChkHeight = 18;
        const int ChkWidth = 120;
        const int ChkPaddingHeight = 5;
        const int GroupBoxPaddingHeight = 10;
        const int ChkPaddingLeft = 10;
        /// <summary>
        /// 显示多少栏
        /// </summary>
        const int ChkColumns = 4;
        #endregion

        /// <summary>
        /// 
        /// </summary>
        public void Export()
        {
            ApplyDelayLoadData();
            this.ShowDialog();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        protected override void DelayLoadData()
        {
            if (IsDisposed)
            {
                return;
            }
            if (DataSource == null)
            {
                MessageBox.Show(LocaleFramework.GetString("@NoDataToExport"));
                btnOK.Enabled = false;
                return;
            }

            // Init check boxes
            if (Config == null)
            {
                if (DataSource is DataTable)
                {
                    InitCheckBoxesFromDataTable();
                }
                else
                {
                    // TODO: 需要改变参数
                    throw new ArgumentException("只有当数据源DataSource的类型为DataTable时，配置信息Config属性方允许为null");
                }
            }
            else
            {
                InitCheckBoxesFromConfig();
            }
        }
        
        private void InitCheckBoxesFromDataTable()
        {
            DataTable dt = dataSource as DataTable;
            CheckBoxX chk = null;
            for (int i = 0; i < dt.Columns.Count;i++ )
            {
                DataColumn column = dt.Columns[i];
                chk = NewCheckBox(column.ColumnName, column.Caption, i);
                chk.BringToFront();
            }

            AdjustPanelAndWindowHeight(chk);
        }

        private void InitCheckBoxesFromConfig()
        {
            List<ColumnInfo> columns = Config.ExportColumns;
            displayColumns = columns;
            CheckBoxX chk = null;
            for (int i = 0; i < columns.Count; i++)
            {
                chk = NewCheckBox(columns[i].Name, columns[i].Caption, i);
            }

            AdjustPanelAndWindowHeight(chk);
        }

        private CheckBoxX NewCheckBox(string name, string caption, int index)
        {
            CheckBoxX chk = new CheckBoxX();
            grpCheckBoxes.Controls.Add(chk);
            chk.Text = caption;
            chk.Name = "chk" + name;
            chk.AutoSize = true;
            chk.BackColor = Color.Transparent;
            chk.FocusCuesEnabled = false;
            chk.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;

            // 18 为chk的高度，5为padding, 150 为checkbox的宽度
            chk.Location = new Point(ChkPaddingLeft + ChkWidth * (index % ChkColumns), (ChkHeight + ChkPaddingHeight) * (index / ChkColumns));

            return chk;
        }

        private void AdjustPanelAndWindowHeight(CheckBoxX chk)
        {
            if (chk != null)
            {
                if (grpCheckBoxes.Height < chk.Location.Y + ChkHeight + ChkPaddingHeight)
                {
                    grpCheckBoxes.Height = chk.Location.Y + ChkHeight + ChkPaddingHeight;
                    grpButtons.Location = new Point(grpCheckBoxes.Location.X, grpCheckBoxes.Location.Y + GroupBoxPaddingHeight);
                    Height = grpButtons.Location.Y + GroupBoxPaddingHeight;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (CheckBoxX chk in grpCheckBoxes.Controls)
            {
                chk.Checked = chkAll.Checked;
            }
        }

        /// <summary>
        /// TODO: 添加导出不同的文件格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }

            if (dataSource == null)
            {
                MessageBox.Show("@NoDataToExport");
                return;
            }

            string[] exportColumns = GetColumnsToExport();
            if (exportColumns != null && exportColumns.Length == 0)
            {
                MessageBox.Show(LocaleFramework.GetString("@CheckColumnsToExport"));
                return;
            }

            DataTable dtToExport = null;
            ListConfigData configData = new ListConfigData(Config, dataSource);

            try
            {
                if (exportColumns == null)
                {
                    dtToExport = configData.ConvertExportData();
                }
                else
                {
                    dtToExport = configData.ConvertExportData(exportColumns);
                }

                // TODO: EXPORT TO FILE
                HtmlExporter exporter = new HtmlExporter();
                exporter.DataTableToHtml(dtToExport, txtPath.Text);

                OpenDownloadDlg dlg = new OpenDownloadDlg();
                dlg.FileName = txtPath.Text;
                dlg.ShowDialog(this);

                DialogResult = DialogResult.OK;
            }
            catch (NotSupportedException ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.ToString());
            }
        }

        private bool CheckData()
        {
            // TODO: CHECK DATA
            if (txtPath.Text.Trim() == "")
            {
                balloon(LocaleFramework.GetString("@SelectOrEnterExportFilePath"), txtPath);
                return false;
            }
            if (File.Exists(txtPath.Text))
            {
                if (DialogResult.Yes != MessageBox.Show(this, LocaleFramework.GetString("@ConfirmReplaceFile"), "", MessageBoxButtons.YesNoCancel))
                {
                    return false;
                }

                try
                {
                    File.Delete(txtPath.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 获取选中的导出的列表，如果是全选，则返回Null
        /// </summary>
        /// <returns></returns>
        private string[] GetColumnsToExport()
        {
            List<string> columns = new List<string>();
            foreach(CheckBoxX chk in grpCheckBoxes.Controls)
            {
                if (chk.Checked)
                {
                    columns.Add(chk.Name.Remove(0, "chk".Length));
                }
            }

            if (columns.Count == grpCheckBoxes.Controls.Count)
            {
                return null;
            }

            return columns.ToArray();
        }

        private void btnGetPath_Click(object sender, EventArgs e)
        {
            fileDlg.FileName = fileDlg.FileName;
            if (fileDlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = fileDlg.FileName;
            }
        }

        
    }
}
